const http = require('http')
const fs = require('fs')
http.createServer(function (request, response) {
    // console.log('run')
    // 发送响应数据 "Hello World"
    //todo流 request response
    //end这个句子好不好？
    // response.end('Hello World\n')
    // response = 'haha'
    // response.body="hihih"
    
    const { url, method,headers} = request;
    if (url === '/' && method === 'GET')
    {
        fs.readFile('index.html', (err, data) => {
            if (err) {
                response.writeHead(500, {
                    'Content-Type': 'text/plain;charset=utf-8'
                })
                response.end('500 服务器炸了')
                return
            }
            response.statusCode = 200;
            response.setHeader('Content-Type', 'text/html')
            response.end(data)
        })
    }
    else if (url === '/users' && method === 'GET')
    {
        response.writeHead(200, { 'Content-Type': 'application/json' })
        response.end(JSON.stringify({name:'Tome'}))
    }
    else if (method === 'GET'&&headers.accept.indexOf('image/*')!==-1)
    {
        //直接用readFile内存占用大 需要加载所哦呦图片内容到服务器
        //stream流 url /1.jpg=>./1.jpg
        fs.createReadStream('.'+url).pipe(response)
    }
    else {
        response.statusCode = 400
        response.setHeader('Content-Type', 'text/plain;charset=utf-8')
        response.end('404 不提供这种服务')
    }
})
.listen(3000, () => {
// 终端打印如下信息
console.log('Server running at 3000');      
});